<?php

namespace App\Service\UserService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\PddToken;
use App\Service\VendorClient\ShopTianhongApi\ShopTianhongApiClient;
use App\Model\PssModel\TianHongGoods;
use Hyperf\Utils\WaitGroup;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;
use App\Amqp\Producer\TianHongMessageProducer;

/**
 * 天虹服务中心
 * @author chenshubo
 */
class TianHongService extends BaseService
{
    protected $TianhongApiClient;
    protected $config;
    protected $extends;
    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType,array $data,array $binfo)
    {
        return $this->{$messageType}($data,$binfo);
    }
    /**
     * 商品消息变化
     * @param array $data
     */
    public function goodsChange(array $data,$binfo)
    {
        $this->config = $config = $this->getConfig($binfo);
        $this->extends = @json_decode($config['extends'],true);
        $this->TianhongApiClient = new ShopTianhongApiClient($config);
        //开启协程
        $count = count($data);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($data as $goods)
        {
            co(function () use ($wg,$goods,& $result_update)
            {
                $response = $this->syncSingleTianhongGoods($goods);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品批量下架
     * @param array $data
     */
    public function goodsSkuChange(array $data,$binfo)
    {
        $config = $this->getConfig($binfo);
        $this->TianhongApiClient = new ShopTianhongApiClient($config);
        $produts = TianHongGoods::instance()
        ->select(['prod_id'])
        ->whereIn('outer_id',$data['skuList'])
        ->whereNotNull('prod_id')
        ->get()
        ->toArray();
        if( empty($produts) ) {
            return Normal::returnCode(Normal::SUC,"没有满足的数据，无须处理");
        }
        //开启协程
        $count = count($produts);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($produts as $prod)
        {
            co(function () use ($wg,$prod,& $result_update)
            {
                $data=[
                    "prod_id"    => $prod["prod_id"],
                    "marketable" => 0,
                ];
                $response = $this->TianhongApiClient->updateProdStatus($data);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品全量下架
     * @param array $data
     */
    public function goodsBatchDown(array $data,$binfo)
    {
        $config = $this->getConfig($binfo);
        $this->TianhongApiClient = new ShopTianhongApiClient($config);
        //先查询出天虹的所有商品
        $page = 1;
        while (true)
        {
            $query = [
                'page_number'   => $page,
                'page_size'     => "10",
            ];
            $result_prod = $this->TianhongApiClient->findMerchantProduct($query);
            //如果没有商品就暂停查询
            if ($result_prod['code'] != Normal::SUC  || empty($result_prod["data"]["product_list"]))
            {
                break;
            }
            $result_prod = $result_prod["data"]["product_list"];
            
            //记录天虹后台商品信息
            $this->addTianhongGoods($result_prod);
            //开始协助并发下架商品
            $prod_count = count($result_prod);
            $wg = new WaitGroup();
            $wg->add($prod_count);
            foreach ($result_prod as $prod)
            {
                $prod_id = $prod["prod_id"];
                co(function () use ($prod_id,$wg) {
                    $data=[
                        "prod_id"    => $prod_id,
                        "marketable" => 0,
                    ];
                    $this->TianhongApiClient->updateProdStatus($data);
                    $wg->done();
                });
            }
            $wg->wait();
            $page++;
        }
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 记录天虹商品
     * @param array $goodsInfo
     */
    public function addTianhongGoods(array $goodsList)
    {
        foreach ($goodsList as $goodsInfo){
            foreach ($goodsInfo["sku_list"] as $goods){
                $skucode = $goods["outer_id"];
                $prod_id = $goodsInfo["prod_id"];
                
                //查询云仓是否记录天虹后台商品id，如果有，就更新，没有，就新增
                $TianhongGood   = TianHongGoods::instance()->info(['outer_id' => $skucode]);
                if(empty($TianhongGood) )
                {
                    TianHongGoods::instance()->add([
                        'outer_id'   => $skucode,
                        'prod_id'    => $prod_id,
                        'part_number'=> $goods["sku_code"],
                        'cd'         => time(),
                    ]);
                }
                else
                {
                    TianHongGoods::instance()->where('outer_id',$skucode)->update([
                        'prod_id'    => $prod_id,
                        'part_number'=> $goods["sku_code"],
                        'md'         => time(),
                    ]);
                }
            }
        }
    }
    /**
     * 同步商品
     * @param array $goods
     */
    public function syncSingleTianhongGoods(array $goodsInfo)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //判断是否向天虹推送过商品，如果有，就执行更新操作，没有执行添加操作
        $TianhongGood   = TianHongGoods::instance()->info(['outer_id' => $skucode]);
        if( !empty($TianhongGood['prod_id']))
        {
            return $this->goodsTianhongUpdate($goodsInfo,$TianhongGood);
        }
        else
        {
            $return = $this->goodsTianhongAdd($goodsInfo,$TianhongGood);
            if( $return['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"商品查询失败【{$return['msg']}】");
            }
            return $this->goodsTianhongUpdate($goodsInfo,$return['data']['TianhongGoods']);
        }
    }


    /**
     * 天虹商品新增
     * @param array $goods
     * @param array $TianhongGood
     */
    public function goodsTianhongAdd(array $goodsInfo,array $TianhongGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList      = current($skuInfo['storeList']);
        $batchFirst     = current($storeList['goods_batch_list']);
        $firstSpec      = current($batchFirst['spec_list']);
        
        if( $firstSpec["spec_num"] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"商品不符合规则【打包价的不推】");
        }
        
        //查询商品是否添加过
        if( empty($TianhongGood))
        {
           //向天虹查询该商品是否有创建
            $pushData = [
                "page_number"     => 1,
                "page_size"       => 1,
                "outer_id"        => $skucode,
            ];
            $result_prod = $this->TianhongApiClient->findMerchantProduct($pushData);
            if( $result_prod['code'] != Normal::SUC )
            {
                return Normal::returnCode(Normal::FAIL,"没查到自编码为【{$skucode}】的数据，请到天虹后台核实是否创建！");
            }
            $prod_id = $result_prod['data']['product_list'][0]['prod_id'];
            if(empty($TianhongGood) )
            {
                TianHongGoods::instance()->add([
                    'outer_id'   => $skucode,
                    'prod_id'    => $prod_id,
                    'cd'         => time(),
                ]);
            }
            else 
            {
                TianHongGoods::instance()->where('outer_id',$skucode)->update([
                    'prod_id'    =>  $prod_id,
                    'md'         => time(),
                ]);
            }
        }
        else
        {
            $prod_id = $TianhongGood['prod_id'];
        }
        
        return Normal::returnCode(Normal::SUC,"处理完成",[
            'TianhongGoods'  => [
                'outer_id'      => $skucode,
                'prod_id'       => $prod_id,
            ]
        ]);        
    }
    
    /**
     * 天虹更新
     * @param array $goods
     * @param array $TianhongGood
     */
    public function goodsTianhongUpdate(array $goodsInfo,array $TianhongGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList     = current($skuInfo['storeList']);
        $batchFirst    = current($storeList['goods_batch_list']);
        $firstSpec     = current($batchFirst['spec_list']);
        $goodsSpecAttr = $goodsInfo["goodsSpecAttr"];
        $prod_id       = $TianhongGood["prod_id"];
        
        
        if( $firstSpec["spec_num"] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"商品不符合规则【打包价的不推】");
        }
       
        //进行批量调用接口
        $goodsUpdateAllprodList = [];
        //SKU 库存单个修改接口
        $goodsUpdateAllprodList[] = [
            'method'    => 'updateSkuStock',
            'data'      => [
                "outer_id"  => $skucode,
                "quantity"  => $batchFirst["num"]
            ]
        ];
        
        //产品更新上/下架
        $goodsUpdateAllprodList[] = [
            'method'    => 'updateProdStatus',
            'data'      => [
                "prod_id"    => $prod_id,
                "marketable" => 1,
            ]
        ];
        //开启协程
        $count = count($goodsUpdateAllprodList);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($goodsUpdateAllprodList as $prod)
        {
            co(function () use ($wg,$prod,& $result_update)
            {
                $response = $this->TianhongApiClient->{$prod['method']}($prod['data']);
                $result_update[] = [
                    'method'    => $prod['method'],
                    'response'  => $response
                ];
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);        
    }
    
    private function getConfig($binfo)
    {
        $where=[
            'auth_type' => PddToken::AUTH_TYPE_TIANHONG,
            'bid'       => $binfo["bid"],
        ];   
        $config = PddToken::instance()->info($where);
        return $config;
    }
}